#pragma once
#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include<sys/wait.h>
#include<signal.h>
#include<pthread.h>
#include"ThreadPool.hpp"
#include"Task.hpp"
#include "Daemon.hpp"
using std::cout;
using std::endl;
using std::string;
const int backlog = 10; // 一般不要设置太大
class TcpServer;
class ThreadData{
    public:
    int _socket;
    string _ip;
    uint16_t _port;
    TcpServer* t;
    ThreadData(int fd,const string& ip,uint16_t port,TcpServer*tt)
        :_socket(fd),
        _ip(ip),
        _port(port)
        ,t(tt)
    {}
};
class TcpServer
{
public:
    TcpServer(const uint16_t &port = 8080, const std::string ip = "0.0.0.0")
        : _listensocket(-1), _port(port), _ip(ip)

    {}
    // static void* Routine(void* args)
    // {
    //     pthread_detach(pthread_self());
    //     auto it =  static_cast<ThreadData*> (args);
        
    //     it->t->Service(it->_socket,it->_ip,it->_port);
    //     delete it;
    //     return nullptr;
    // }
    void Init()
    {
        _listensocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensocket < 0)
        {
            cout << "create socket fail\n";
            exit(-1);
        }
        cout << "create socket success, socket: " << _listensocket << endl;
        int opt = 1;
        setsockopt(_listensocket, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT, &opt, sizeof(opt)); // 防止偶发性的服务器无法进行立即重启(tcp协议的时候再说)

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        inet_aton(_ip.c_str(), &local.sin_addr); // aton
        local.sin_port = htons(_port);           // 转为网络字节序
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        int n = bind(_listensocket, (struct sockaddr *)&local, len);
        if (n < 0)
        {
            cout << "bind fail " << endl;
            exit(-2);
        }
        cout << "bind success,bind port: " << _port << endl;
        // Tcp是面向连接的,服务器一般是比较"被动的",服务器一直处于一种一直在等待连接到来的
        // 状态

        // 设为监听状态
        if (listen(_listensocket, backlog) < 0)
        {
            cout << "listen error\n";
            exit(-3);
        }
        cout << "listen success\n";
    }
    void Run()
    {
        // signal(SIGCHLD,SIG_IGN);
        // signal(SIGPIPE,SIG_IGN);
        Daemon();

        ThreadPool<Task>::GetInstance()->Start();
        while (true) // for(;;)
        {
            // 1.获取新连接
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int socketfd = accept(_listensocket, (sockaddr *)&client, &len);
            if (socketfd < 0)
            {
                cout << "accept fail,continue accept\n";
                continue;
            }
            uint16_t port = ntohs(client.sin_port);
            char ipstr[32];
            // socklen_t len = sizeof(ipstr);
            inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
            cout << "accept success" << endl;
            cout << "client ip:" << ipstr << endl;
            cout << "client str:" << port << endl;
            ThreadData* td = new ThreadData(socketfd,ipstr,port,this);
            // 2.根据新连接来通信
            //Version 1  单进程
            //  Service(socketfd, ipstr, port);
            // close(socketfd);

            //version 2 多进程版
            // pid_t pid = fork();
            // if(pid == 0)
            // {
            //     //子进程
            //     close(_listensocket);
            //     if(fork() > 0) exit(0);
            //     //这样如果是父进程，也就是本来的进程，就退出了，下面正常wait，然后去进行新的accept
            //     //如果是子进程，正常执行下面的代码
            //     Service(socketfd, ipstr, port); //孙子进程 被系统领养
            //     close(socketfd);
            //     exit(0);
            // }
            // close(socketfd);
            // pid_t rid = waitpid(pid,nullptr,0);

            //3.version 3 多线程版本
            // pthread_t tid;
            // pthread_create(&tid,nullptr,Routine,(void*)td);
            
            //4 version 4---线程池版
            Task t(socketfd,ipstr,port);
            ThreadPool<Task>::GetInstance()->Push(t);
        }
    }
    ~TcpServer() {}

private:
    // static void Service(int socketfd, const string &ip, const uint16_t port)
    // {
    //     char buff[1024];
    //     while (true)
    //     {
    //         ssize_t n = read(socketfd, buff, sizeof(buff));
    //         if (n > 0)
    //         {
    //             buff[n] = '\0';
    //             cout << buff << endl;
    //             string echo_string = "tcpserver echo#";
    //             echo_string += buff;
    //             write(socketfd, echo_string.c_str(), echo_string.size());
    //         }
    //         else if(n == 0)
    //         {
    //             cout << "quit !" << endl;
    //             break;
    //         }
    //         else{
    //             cout << "error" << endl;
    //             exit(3);
    //         }
    //     }
    // }
    int _listensocket;
    uint16_t _port;
    std::string _ip;
};